<template>
  <div>
    <app-head></app-head>
    <app-body>
      <div class="tea-details-container">
        <el-button style="margin: 10px 0" @click="goback()">返回</el-button>
        <div class="details-header">
          <div class="details-header-user-info">
            <el-image
                style="width: 80px; height: 80px;border-radius: 5px;"
                :src="$store.state.baseApi + science.user.avatar"
                fit="contain"></el-image>
            <div style="margin-left: 10px;">
              <div class="details-header-user-info-nickname"> 发布者：{{ science.user.nickname }}</div>
              <div class="details-header-user-info-time"> 于{{ science.user.signInTime.substring(0, 10) }}加入平台
              </div>
            </div>
          </div>
        </div>


        <div class="details-picture">
          <div class="details-info">
<!--            <div class="details-info-main"><span class="details-info-title">商品编号：</span>{{ science.scienceId }}</div>-->
            <div class="details-info-main"><span class="details-info-title">视频名称：</span>{{ science.scienceName }}
            </div>
          </div>
          <video width="100%" :src="'http://localhost:9321/'+science.scienceUrl" controls="false"></video>
        </div>
        <el-button :type="liked ? 'success' : 'info'" @click="likeButton()">
          {{ liked ? '取消点赞' : '点赞' }}
        </el-button>
        <el-button :type="isFavorite ? 'success' : 'info'" @click="favoriteButton()">
          {{ isFavorite ? '取消收藏' : '收藏' }}
        </el-button>
<!--        <el-button :type="liked ? 'success' : 'info'" @click="toggleLike">-->
<!--          {{ liked ? '已点赞' : '点赞' }}-->
<!--        </el-button>-->
<!--        <el-button :type="liked ? 'success' : 'info'" @click="favoriteButton(science)">-->
<!--          {{ isFavorite ? ' 取消收藏' : ' 收藏' }}-->
<!--        </el-button>-->
        </div>

        <div class="message-container" id="replyMessageLocation">
          <div class="message-title">全部留言</div>
          <div class="message-send">
            <div v-if="isReply" style="padding-bottom: 10px;">
              <el-button type="info" @click="cancelReply">回复：{{ replyData.toMessage }} @{{ replyData.toUserNickname }}
                <i class="el-icon-close el-icon--right"></i></el-button>
            </div>
            <el-input
                type="textarea"
                autosize
                placeholder="留言提问..."
                v-model="messageContent"
                maxlength="200"
                show-word-limit>
            </el-input>
            <div class="message-send-button">
              <el-button @click="sendMessage" type="success"> 发送留言</el-button>
            </div>
          </div>
          <div>
            <div v-for="(mes,index) in messageList" :key="index" class="message-container-list">
              <div class="message-container-list-left">
                <el-image
                    style="width: 55px; height: 55px;border-radius: 5px;"
                    :src="$store.state.baseApi + mes.fromU.avatar"
                    fit="contain"></el-image>
                <div class="message-container-list-text">
                  <div class="message-nickname">{{ mes.fromU.nickname }}
                    {{
                      mes.toU.nickname ? ' @' + mes.toU.nickname + '：' +
                          mes.toM.content.substring(0, 10) +
                          (mes.toM.content.length > 10 ? '...' : '') : ''
                    }}
                  </div>
                  <div class="message-content">{{ mes.content }}</div>
                  <div class="message-time">{{ mes.createTime }} <span style="color: red" v-if="(mes.userId == shUserId)"  @click="delMessage(index)">删除</span></div>
                </div>
              </div>
              <div class="message-container-list-right">
                <el-button style="float: right;" plain @click="replyMessage(index)"> 回复</el-button>
              </div>
            </div>
          </div>
        </div>
    </app-body>
    <app-foot></app-foot>
  </div>
</template>

<script>
import AppHead from '../common/AppHeader.vue';
import AppBody from '../common/AppPageBody.vue'
import AppFoot from '../common/AppFoot.vue'
import axios from "axios";

export default {
  name: "tea-details",
  components: {
    AppHead,
    AppBody,
    AppFoot
  },
  data() {
    return {
      liked: true,
      favor:false,
      messageContent: '',
      toUser: null,
      toMessage: null,
      isReply: false,
      replyData: {
        toUserNickname: '',
        toMessage: ''
      },
      messageList: [],
      science: {
        scienceId: '',
        scienceName: '',
        scienceTitle: '',
        scienceType: '',
        scienceStatus: -1,
        userId: '',
        user: {
          avatar: '',
          nickname: '',
          signInTime: ''
        },
      },
      isMaster: false,
      isFavorite: true,
      favoriteId: 0,
      likeId: 0,
      shUserId:0,
    };
  },
  mounted() {
    let id = this.$route.query.id;
    this.$api.getscience({
      id: id
    }).then(res => {
      console.log(res);
      if (res.data) {
        this.science = res.data;
        let userId = this.getCookie('shUserId');
        if (userId == this.science.userId) {
          console.log('isMaster');
          this.isMaster = true;
        }
        this.checkFavorite();
        this.getAllteaMessage();
      }
    });
  },
  methods: {
    getAllteaMessage() {
      this.shUserId = this.getCookie('shUserId')
      this.$api.getAllteaMessage({
        teaId: this.science.scienceId
      }).then(res => {
        console.log('getAllteaMessage', res);
        if (res.status_code === 1) {
          this.messageList = res.data;
        }
      }).catch(() => {
      })
    },
    checkFavorite() {
      this.$api.checkFavorite({
        teaId: this.science.scienceId
      }).then(res => {
        if (!res.data) {
          this.isFavorite = false;
        } else {
          this.favoriteId = res.data;
        }
      })
      this.$api.checkLike({
        teaId: this.science.scienceId
      }).then(res => {
        if (!res.data) {
          this.liked = false;
        } else {
          this.likeId = res.data;
        }
      })
    },
    getCookie(cname) {
      var name = cname + "=";
      var ca = document.cookie.split(';');
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
      }
      return "";
    },
    replyMessage(index) {
      $('html,body').animate({
        scrollTop: $("#replyMessageLocation").offset().top - 600
      }, {duration: 500, easing: "swing"});
      this.isReply = true;
      this.replyData.toUserNickname = this.messageList[index].fromU.nickname;
      this.replyData.toMessage = this.messageList[index].content.substring(0, 10) + (this.messageList[index].content.length > 10 ? '...' : '');
      this.toUser = this.messageList[index].userId;
      this.toMessage = this.messageList[index].id;
    },
    delMessage(index) {
      this.$api.deleteMessage({
        id: this.messageList[index].id,
      }).then(res => {
        location.reload();
      }).catch(() => {
      })
    },
    favoriteButton() {
      if (this.isFavorite) {
        this.$api.deleteFavorite({
          id: this.favoriteId
        }).then(res => {
          console.log(res);
          if (res.status_code === 1) {
            this.$message({
              message: '已取消收藏！',
              type: 'success'
            });
            this.isFavorite = false;
          } else {
            this.$message.error(res.msg)
          }
        }).catch(e => {
        })
      } else {
        this.$api.addFavorite({
          teaId: this.science.scienceId
        }).then(res => {
          console.log(res);
          if (res.status_code === 1) {
            this.$message({
              message: '已收藏！',
              type: 'success'
            });
            this.isFavorite = true;
            this.favoriteId = res.data;
          } else {
            this.$message.error(res.msg)
          }
        }).catch(e => {
        })
      }
    },
    likeButton() {
      if (this.liked) {
        this.$api.deleteLike({
          id: this.likeId
        }).then(res => {
          console.log(res);
          if (res.status_code === 1) {
            this.$message({
              message: '已取消喜欢！',
              type: 'success'
            });
            this.liked = false;
          } else {
            this.$message.error(res.msg)
          }
        }).catch(e => {
        })
      } else {
        this.$api.addLike({
          teaId: this.science.scienceId
        }).then(res => {
          console.log(res);
          if (res.status_code === 1) {
            this.$message({
              message: '已加入喜欢！',
              type: 'success'
            });
            this.liked = true;
            this.likeId = res.data;
          } else {
            this.$message.error(res.msg)
          }
        }).catch(e => {
        })
      }
    },
    cancelReply() {
      this.isReply = false;
      this.toUser = this.science.userId;
      this.toMessage = null;
      this.replyData.toUserNickname = '';
      this.replyData.toMessage = '';
    },
    sendMessage() {
      let content = this.messageContent.trim();
      if (this.toUser == null) {
        this.toUser = this.science.userId;
      }
      if (content) {
        let contentList = content.split(/\r?\n/);
        let contenHtml = contentList[0];
        for (let i = 1; i < contentList.length; i++) {
          contenHtml += '<br>' + contentList[i];
        }
        this.$api.sendMessage({
          teaId: this.science.scienceId,
          content: contenHtml,
          toUser: this.toUser,
          toMessage: this.toMessage
        }).then(res => {
          if (res.status_code === 1) {
            this.$message({
              message: '留言成功！',
              type: 'success'
            });
            this.messageContent = '';
            this.cancelReply();
            this.getAllteaMessage();
          } else {
            this.$message.error("留言失败！" + res.msg);
          }
        }).catch(() => {
          this.$message.error("留言失败！");
        });

      } else {
        this.$message.error("留言为空！");
      }
    },
    goback() {
      this.$router.back()
    }
  }
}
</script>

<style scoped>
.tea-details-container {
  min-height: 85vh;
}

.details-header {
  height: 80px;
  border-bottom: 10px solid #f6f6f6;
  display: flex;
  justify-content: space-between;
  padding: 20px;
  align-items: center;
}

.details-header-user-info {
  display: flex;
}

.details-header-user-info-nickname {
  font-size: 22px;
  margin-bottom: 10px;
}

.details-header-user-info-time {
  font-size: 16px;
  color: #555555;
}

.details-header-buy {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  width: 280px;
}

.details-info {
  padding: 20px 50px;
}

.details-info-title {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 20px;

}

.details-info-main {
  font-size: 28px;
  color: #121212;
}

.message-container {
  min-height: 100px;
  border-top: 10px solid #f6f6f6;
  padding: 20px;
}

.message-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
}

.message-send {
  min-height: 60px;
}

.message-send-button {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.message-container-list {
  min-height: 60px;
  border-top: 1px solid #eeeeee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
}

.message-container-list:first-child {
  border-top: none;
}

.message-container-list-left {
  width: 850px;
  display: flex;
}

.message-container-list-right {
  width: 100px;
}

.message-container-list-text {
  margin-left: 10px;
}

.message-nickname {
  font-weight: 600;
  font-size: 18px;
  padding-bottom: 5px;
}

.message-content {
  font-size: 16px;
  padding-bottom: 15px;
  color: #555555;
  width: 770px;
}

.message-time {
  font-size: 13px;
  color: #555555;
}
</style>